
'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url client/pages/order/kh/create_order 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let { uid ,product_list,remarks,type} = data;
		let res = { code: 0, msg: "" };
		// 业务逻辑开始-----------------------------------------------------------
		
		
		let porduct_id_list = product_list.map((item) =>{ return item.merchandise_id})
		
		console.time()
		let info = await vk.baseDao.select({
		  getCount: false, // 是否需要同时查询满足条件的记录总数量，默认false
		  getMain: true, // 是否只返回rows数据，默认false
		  pageIndex: 1, // 当前第几页
		  pageSize: 500, // 每页条数
		  dbName: "daoju_merchandise",
		  whereJson: {
		    _id : _.in(porduct_id_list)
		  }
		});
		console.timeEnd()
		function findNumById(array, _id) {
		    const item = array.find(element => element._id === _id);
		    return item ? item.inventory : null;
		}
		
		let inventory_status = product_list.every(item => {
		    const bNum = findNumById(info, item.merchandise_id);
			console.log('bNum',bNum,item.merchandise_id)
		    return bNum !== null && item.number <= bNum;
		});
		
		if(!inventory_status){
			return {
				code:-1,
				msg:"选择的商品库存不足"
			}
		}
		
		function findPriceById(array,_id){
			const item = array.find(element => element._id === _id);
			return item ? item.price : 0;
		}
		
		console.log("创建订单",product_list)
		
		console.log("最新价格",info)
		let all_price = product_list.reduce((per,cur) => {
			let price = findPriceById(info, cur.merchandise_id)
			let num = cur.number
			return per + (price * num)
		},0)
		
		let no = vk.pubfn.createOrderNo("NO");
		
		let filter_product_list = product_list.map((item) => {
			return {
				merchandise_id:item.merchandise_id,
				title:item.title,
				image:item.image,
				nickname:item.nickname,
				price:item.price,
				classification_name:item.classification_name,
				number:item.number
			}
		})
	
		
		let order_info = {
			out_trade_no:no, //订单号
			amount:all_price *100, //订单金额 单位分
			amount_payment:0, //实际付款
			status:0, // 订单状态0未支付 1已支付/待核销 3已领取 4待归还/待核销 5已归还   -1/过期
			remarks,
			product_list:filter_product_list,
			create_time:new Date().getTime(),
			status: all_price > 0 ? 0 : 1,
			user_id:userInfo._id,
			nickname:userInfo.nickname,
			platform:"wxpay",
			payment_type:'直接付款',//直接付款 余额支付 直接付款+余额 
			invite_code:userInfo.invite_code,
			os_name:userInfo.register_env.os_name,
			// expire_time:new Date().getTime()+ 900000
			expire_time: new Date().getTime()+13500000
		}
		
		const result = await vk.baseDao.add({
			dbName:"daoju_order",
			dataJson:order_info
		})
		
		// 扣除库存
		for(let item of filter_product_list){
			console.log('item',item)
			await vk.baseDao.update({
			  dbName: "daoju_merchandise", // 表名
			  whereJson: { // 条件
			    _id: item.merchandise_id,
			  },
			  dataJson: { // 需要修改的数据
			    inventory: _.inc(item.number * -1)
			  }
			});
		}
		
		// 扣除购物车
		if(type === 'car'){
			for(let item of filter_product_list){
				await vk.baseDao.del({
				  dbName: "daoju_shopcart", // 表名
				  whereJson: { // 条件
					merchandise_id: item.merchandise_id,
					user_id:uid
				  },
				});
			}
		}
		
		res.out_trade_no = no
		if(result){
			
			res.msg = '订单创建成功'
			res.all_price = all_price
			return res
		}
		
	
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}